﻿using BasicData.API.Application.Command;
using BasicData.API.Application.Mediator;
using BasicData.API.Dtos;
using BasicData.API.Services;
using BasicData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Linq;

namespace BasicData.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]

    public class MangeController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IProductionInfoMediator productionInfoMediator;
        private readonly IUserMediator userMediator;
        private readonly ICaptchaService captchaService;
        private readonly IGoodsMediator goodsMediator;

        public MangeController(
            IMediator mediator, 
            IProductionInfoMediator productionInfoMediator, 
            IUserMediator userMediator,
            ICaptchaService captchaService,
            IGoodsMediator goodsMediator)
        {
            this.mediator = mediator;
            this.productionInfoMediator = productionInfoMediator;
            this.userMediator = userMediator;
            this.captchaService = captchaService;
            this.goodsMediator = goodsMediator;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="command">登录命令</param>
        /// <returns>登录结果</returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<APIResult<UserDTO>> LoginUser(LoginQueryCommand command)
        {
            return await userMediator.LoginAsync(command);
        }
        
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="command">注册命令</param>
        /// <returns>注册结果</returns>
      
        [HttpPost("register")]
        public async Task<APIResult<UserDTO>> RegisterUser(RegisterUserCommand command)
        {
            try
            {
                // 使用中介者注册用户
                return await userMediator.RegisterAsync(command);
            }
            catch (Exception ex)
            {
                return new APIResult<UserDTO>
                {
                    Code = ResultCode.添加失败,
                    Message = $"用户注册失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns>验证码信息</returns>
        [AllowAnonymous]
        [HttpGet("captcha")]
        public async Task<ActionResult<CaptchaGenerateResponse>> GetCaptcha()
        {
            try
            {
                var request = new CaptchaGenerateRequest
                {
                    Width = 120,
                    Height = 40,
                    Length = 4,
                    ExpireMinutes = 5
                };
                
                var response = await captchaService.GenerateCaptchaAsync(request);
                
                // 返回包含完整Base64图片数据的响应
                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"生成验证码失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 刷新验证码
        /// </summary>
        /// <param name="captchaId">验证码ID</param>
        /// <returns>新的验证码信息</returns>
        [AllowAnonymous]
        [HttpGet("captcha/refresh/{captchaId}")]
        public async Task<ActionResult<CaptchaGenerateResponse>> RefreshCaptcha(string captchaId)
        {
            try
            {
                if (string.IsNullOrEmpty(captchaId))
                {
                    return BadRequest(new { message = "验证码ID不能为空" });
                }
                
                var request = new CaptchaGenerateRequest
                {
                    Width = 120,
                    Height = 40,
                    Length = 4,
                    ExpireMinutes = 5
                };
                
                var response = await captchaService.RefreshCaptchaAsync(captchaId, request);
                
                // 返回包含完整Base64图片数据的响应
                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"刷新验证码失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="request">验证请求</param>
        /// <returns>验证结果</returns>
        [AllowAnonymous]
        [HttpPost("captcha/verify")]
        public async Task<ActionResult<CaptchaVerifyResponse>> VerifyCaptcha([FromBody] CaptchaVerifyRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var response = await captchaService.VerifyCaptchaAsync(request);
                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"验证验证码失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取所有生产信息
        /// </summary>
        /// <returns>生产信息列表</returns>
       
        [HttpGet("production-info")]
        public async Task<APIResult<List<ProductionInfoDTO>>> GetAllProductionInfos()
        {
            return await productionInfoMediator.GetAllProductionInfosAsync();
        }
        
        /// <summary>
        /// 添加生产信息
        /// </summary>
        /// <param name="command">添加生产信息命令</param>
        /// <returns>添加结果</returns>
        [HttpPost("production-info")]
        public async Task<APIResult<ProductionInfoDTO>> AddProductionInfo(AddProductionInfoCommand command)
        {
            try
            {
                // 设置创建人信息（在实际应用中可从身份验证中获取）
                command.CreatedBy = command.CreatedBy ?? $"User_{DateTime.Now.Ticks % 1000}";
                
                // 使用中介者添加生产信息
                return await productionInfoMediator.AddProductionInfoAsync(command);
            }
            catch (Exception ex)
            {
                return new APIResult<ProductionInfoDTO>
                {
                    Code = ResultCode.添加失败,
                    Message = $"添加生产信息失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 批量删除生产信息（软删除）
        /// </summary>
        /// <param name="command">批量删除命令</param>
        /// <returns>删除结果</returns>
        [HttpPost("production-info/batch-delete")]
        public async Task<APIResult<bool>> BatchDeleteProductionInfos(BatchDeleteProductionInfoCommand command)
        {
            try
            {
                // 设置修改人信息（在实际应用中可从身份验证中获取）
                command.ModifiedBy = command.ModifiedBy ?? $"User_{DateTime.Now.Ticks % 1000}";
                
                // 使用中介者批量删除生产信息
                return await productionInfoMediator.BatchDeleteProductionInfosAsync(command);
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ResultCode.删除失败,
                    Message = $"批量删除生产信息失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns>商品列表</returns>
     
        [HttpGet("goods")]
        public async Task<APIResult<List<GoodsDTO>>> GetGoods()
        {
            try
            {
                var command = new GetGoodsCommand();

                // 使用中介者获取商品列表
                return await goodsMediator.GetGoodsAsync(command);
            }
            catch (Exception ex)
            {
                return new APIResult<List<GoodsDTO>>
                {
                    Code = ResultCode.查询成功,
                    Message = $"获取商品列表失败: {ex.Message}"
                };
            }
        }
    }
}
